# ai chat: https://www.doubao.com/thread/w5ee0ace083672995
# First do: pip install prettytable

# Example Usage:
# python list-all-branch-cli.py --owner EEPPEE_admin --repo go-service-example --show-tree-url  --plain
# python .\list-all-branch-cli.py --owner eeppee_admin --repo go-service-example --token 977c294d6b1df48b8ed084bb7b9b3bdea9f06b229299e9d5e45de6e98b5f71df


import argparse
import requests
import json
import os
from prettytable import PrettyTable
from datetime import datetime
import textwrap
from pathlib import Path

TOKEN_FILE = Path.home() / '.gitee_branch_viewer_token'

def save_token(token):
    """保存访问令牌到文件"""
    try:
        with open(TOKEN_FILE, 'w') as f:
            f.write(token)
        # 设置文件权限为只有当前用户可读写
        os.chmod(TOKEN_FILE, 0o600)
        print("访问令牌已保存")
    except Exception as e:
        print(f"保存令牌时出错: {e}")

def display_tree_urls(branches, owner, repo, show_table=True):
    """单独打印仓库树URL"""
    if not branches:
        print("未找到分支信息")
        return
    
    tree_urls = []
    for branch in branches:
        branch_name = branch.get("name", "N/A")
        tree_url = f"https://gitee.com/{owner}/{repo}/tree/{branch_name}"
        tree_urls.append(tree_url)
    
    # 打印表格形式（默认）
    if show_table:
        table = PrettyTable()
        table.field_names = ["分支名称", "仓库树链接"]
        table.align = "l"
        
        for branch, url in zip(branches, tree_urls):
            branch_name = branch.get("name", "N/A")
            table.add_row([branch_name, url])
        
        print(table)
    # 打印纯文本列表（每行一个URL）
    else:
        print("\n仓库树链接列表:")
        for url in tree_urls:
            print(url)
    
    # 统计URL数量
    print(f"\n共找到 {len(tree_urls)} 个仓库树链接")
    return tree_urls

def load_token():
    """从文件加载访问令牌"""
    if TOKEN_FILE.exists():
        try:
            with open(TOKEN_FILE, 'r') as f:
                return f.read().strip()
        except Exception as e:
            print(f"加载令牌时出错: {e}")
    return None

def fetch_branches(owner, repo, token):
    """获取Gitee仓库的分支信息"""
    url = f"https://gitee.com/api/v5/repos/{owner}/{repo}/branches"
    headers = {
        "Authorization": token
    }
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP错误发生: {http_err}")
        print(f"响应内容: {response.text}")
        return []
    except Exception as err:
        print(f"其他错误发生: {err}")
        return []

def format_date(date_str):
    """格式化日期字符串"""
    if not date_str:
        return "N/A"
    try:
        # 处理带时区的日期格式
        date_obj = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
        return date_obj.strftime('%Y-%m-%d %H:%M:%S')
    except ValueError:
        return date_str

def display_branches(branches, show_commit_url=False, show_tree_url=False, owner=None, repo=None):
    """美观地展示分支信息"""
    if not branches:
        print("未找到分支信息")
        return
    
    table = PrettyTable()
    columns = ["分支名称", "最后提交者", "提交日期", "提交信息"]
    
    if show_commit_url:
        columns.append("提交链接")
    if show_tree_url:
        columns.append("仓库树链接")
    
    table.field_names = columns
    table.align["分支名称"] = "l"
    table.align["最后提交者"] = "l"
    table.align["提交日期"] = "l"
    table.align["提交信息"] = "l"
    
    if show_commit_url:
        table.align["提交链接"] = "l"
    if show_tree_url:
        table.align["仓库树链接"] = "l"
    
    commit_urls = []
    tree_urls = []
    
    for branch in branches:
        branch_name = branch.get("name", "N/A")
        
        commit = branch.get("commit", {})
        commit_info = commit.get("commit", {})
        
        author = commit_info.get("author", {})
        author_name = author.get("name", "N/A")
        
        date = author.get("date", "")
        formatted_date = format_date(date)
        
        message = commit_info.get("message", "N/A")
        # 限制提交信息长度为80个字符，并在需要时换行
        wrapped_message = textwrap.fill(message, 80)
        
        row = [branch_name, author_name, formatted_date, wrapped_message]
        
        # 添加提交链接
        if show_commit_url:
            commit_url = commit.get("url", "N/A")
            row.append(commit_url)
            commit_urls.append(commit_url)
        
        # 添加仓库树链接
        if show_tree_url and owner and repo:
            tree_url = f"https://gitee.com/{owner}/{repo}/tree/{branch_name}"
            row.append(tree_url)
            tree_urls.append(tree_url)
        
        table.add_row(row)
    
    print(table)
    
    # 统计URL
    url_stats = {}
    if show_commit_url:
        for url in commit_urls:
            if url and url != "N/A":
                domain = url.split('/')[2] if len(url.split('/')) > 2 else "unknown"
                url_stats[domain] = url_stats.get(domain, 0) + 1
    
    if show_tree_url:
        for url in tree_urls:
            if url and url != "N/A":
                # 提取域名和路径模式
                parts = url.split('/')
                if len(parts) > 3:
                    domain = parts[2]
                    path_pattern = f"{parts[3]}/{parts[4]}/tree/*"
                    key = f"{domain}{path_pattern}"
                    url_stats[key] = url_stats.get(key, 0) + 1
                else:
                    domain = "unknown"
                    url_stats[domain] = url_stats.get(domain, 0) + 1
    
    if url_stats:
        print("\nURL统计:")
        for key, count in url_stats.items():
            # print(f"{key}: {count}个链接")
            print(f"{count}个链接")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='查看Gitee仓库的分支信息并统计URL')
    parser.add_argument('--owner', required=True, help='仓库所有者')
    parser.add_argument('--repo', required=True, help='仓库名称')
    parser.add_argument('--token', help='Gitee API访问令牌')
    parser.add_argument('--save-token', action='store_true', help='保存访问令牌以便将来使用')
    parser.add_argument('--show-commit-url', action='store_true', help='在表格中显示提交链接并统计')
    parser.add_argument('--show-tree-url', action='store_true', help='在表格中显示仓库树链接并统计')
    parser.add_argument('--plain', action='store_true', help='纯文本格式输出URL（每行一个）')
    args = parser.parse_args()
    
    # 获取令牌：优先使用命令行参数，否则尝试从文件加载
    token = args.token
    if not token:
        token = load_token()
        if not token:
            print("错误: 未提供访问令牌，且未找到保存的令牌")
            return
    
    # 保存令牌（如果指定了--save-token选项或提供了新令牌）
    if args.save_token or (args.token and token != args.token):
        save_token(args.token)
    
    branches = fetch_branches(args.owner, args.repo, token)
    display_branches(
        branches, 
        show_commit_url=args.show_commit_url, 
        show_tree_url=args.show_tree_url,
        owner=args.owner,
        repo=args.repo,
    )
    display_tree_urls(branches, args.owner, args.repo, show_table=not args.plain)


if __name__ == "__main__":
    main()